package aiku.numericalcontroloa.Service.Impl;

import aiku.numericalcontroloa.Base.Utils.BaseEnum;
import aiku.numericalcontroloa.Base.Utils.HttpStatus;
import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.*;
import aiku.numericalcontroloa.Mapper.MasterControl.MessageNotificationMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderBillingMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderMapper;
import aiku.numericalcontroloa.Model.Dto.ClientsDto;
import aiku.numericalcontroloa.Model.Entity.*;
import aiku.numericalcontroloa.Model.Entity.MasterControl.MessageNotification;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.Order;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.OrderBilling;
import aiku.numericalcontroloa.Model.Vo.*;
import aiku.numericalcontroloa.Service.ClientsService;
import aiku.numericalcontroloa.enums.RoleEnum;
import aiku.numericalcontroloa.project.system.mapper.SysRoleMapper;
import aiku.numericalcontroloa.project.system.pojo.entity.SysRole;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author 马
 * @description 针对表【clients】的数据库操作Service实现
 * @createDate 2024-01-26 09:49:58
 */
@Service
public class ClientsServiceImpl extends ServiceImpl<ClientsMapper, Clients>
        implements ClientsService {
    @Autowired
    private ClientsMapper clientsMapper;
    @Autowired
    private ClientsCacheMapper clientsCacheMapper;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private ChatMapper chatMapper;
    @Autowired
    private RegionCodeZftMapper regionCodeZftMapper;
    @Autowired
    private ClockMapper clockMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SuppliersMapper suppliersMapper;
    @Autowired
    private PurchaseOrdersMapper purchaseOrdersMapper;
    @Autowired
    private PaymentBillingMapper billsMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderBillingMapper orderBillingMapper;
    @Autowired
    private RemarksMapper remarksMapper;
    @Autowired
    private MessageNotificationMapper msgNotificationMapper;
    @Autowired
    private CurrentMapper currentMapper;

    /**
     * 查询所有客户信息，管理员可查询所有，业务员只能查询自己的,分页查询
     * 
     * @return
     */
    @Override
    public ClientsInfoVo clientList(Page<Clients> page, String address, String type) {
        String userid = StpUtil.getLoginId().toString();
        // 先查询是否是管理员,不是管理员，查询自己的客户信息
        User user = userService.isAdmin(userid);
        LambdaQueryWrapper<Clients> queryWrapper = new LambdaQueryWrapper<>();
        if (user == null) {
            User userTwo = userMapper.selectById(userid);
            queryWrapper.eq(Clients::getSalesmanId, userTwo.getId());
        }
        if (address != null && !address.equals("")) {
            // address是字符串拼接的使用,分割的，需要转换成数组
            String[] split = address.split(",");
            queryWrapper.eq(Clients::getProvince, split[0]);
            queryWrapper.eq(Clients::getCity, split[1]);
            queryWrapper.eq(Clients::getDistrict, split[2]);
        }
        if (type != null && !type.equals("")) {
            if (!type.equals("4")) {
                queryWrapper.eq(Clients::getType, type);
            }
        }
        // queryWrapper.eq(Clients::getStatus,0);
        queryWrapper.orderByDesc(Clients::getCreateTime);
        List<Clients> clientsList = clientsMapper.selectPage(page, queryWrapper).getRecords();
        if (clientsList.size() < 1) {
            return new ClientsInfoVo();
        }
        // 拿出id
        List<String> idList = clientsList.stream().map(clients -> clients.getId()).collect(Collectors.toList());
        // 查询交流记录
        List<Chat> chatsList = chatMapper.selectList(new LambdaQueryWrapper<Chat>().in(Chat::getClientsId, idList));
        Map<String, Chat> chatsMap = chatsList.parallelStream() // 使用并行流来加速处理过程
                .filter(chat -> chat.getClientsId() != null) // 确保clientsId非空
                .collect(Collectors.toMap(
                        Chat::getClientsId, // 键由Chat::getClientsId决定
                        Function.identity(), // 值就是流中的对象本身
                        (chat1, chat2) -> chat2 // 在遇到重复键时保留最后一个出现的Chat对象
                ));
        // 拿到所以公司名称
        List<String> supName = clientsList.stream().map(Clients::getCompany).collect(Collectors.toList());
        // 查询约谈内容
        List<Clock> clockList = clockMapper.selectList(new LambdaQueryWrapper<Clock>().in(Clock::getClientsId, idList));
        Map<String, Clock> clockMap = clockList.stream()
                .collect(Collectors.toMap(Clock::getClientsId, Function.identity()));

        // //通过客户的公司名称,去供应商查询该公司总欠款金额
        // LambdaQueryWrapper<Suppliers> queryWrapper1 = new LambdaQueryWrapper<>();
        // queryWrapper1.in(Suppliers::getSuppliersName, supName);
        // List<Suppliers> suppliersList = suppliersMapper.selectList(queryWrapper1);
        //
        // //供应商列表不为空
        // Map<String, String> gysMap = new HashMap<>();
        // Map<String, BigDecimal> leMap = new HashMap<>();
        // if (suppliersList.size()>0){
        // //拿出所以供应商id
        // List<String> supIdList =
        // suppliersList.stream().map(Suppliers::getSuppliersId).collect(Collectors.toList());
        // //供应商id,公司名称
        // gysMap =
        // suppliersList.stream().collect(Collectors.toMap(Suppliers::getSuppliersName,Suppliers::getSuppliersId));
        // //供应商id，欠款金额
        // leMap =
        // suppliersList.stream().collect(Collectors.toMap(Suppliers::getSuppliersId,
        // element -> new BigDecimal("0")));
        //
        // //一个供应商id对应一个公司
        // LambdaQueryWrapper<PurchaseOrders> queryWrapper2 = new
        // LambdaQueryWrapper<>();
        // queryWrapper2.in(PurchaseOrders::getSuppliersId,supIdList);
        // List<PurchaseOrders> purchaseOrderList =
        // purchaseOrdersMapper.selectList(queryWrapper2);
        // if (purchaseOrderList.size()>0){
        // //采购订单id，绑定供应商id
        // Map<String, String> productsIdMap =
        // purchaseOrderList.stream().collect(Collectors.toMap(PurchaseOrders::getProductsId,
        // PurchaseOrders::getSuppliersId));
        // //采购订单id
        // List<String> productsIdList =
        // purchaseOrderList.stream().map(PurchaseOrders::getProductsId).collect(Collectors.toList());
        // //通过采购订单id去账单查询该公司总欠款金额
        // LambdaQueryWrapper<PaymentBilling> queryWrapper3 = new
        // LambdaQueryWrapper<>();
        // queryWrapper3.in(PaymentBilling::getOrderId,productsIdList);
        // //这就是所有公司总欠款金额,再通过订单id来进行金额统计
        // List<PaymentBilling> billsList = billsMapper.selectList(queryWrapper3);
        // for (PaymentBilling bills : billsList) {
        // String prid = productsIdMap.get(bills.getOrderId());
        // //在该公司总欠款金额上加上该订单的金额，修改map的val,使用residue_periods*phase_amount
        //
        // leMap.put(prid,leMap.get(prid).add(bills.getPhaseAmount().multiply(new
        // BigDecimal(bills.getResiduePeriods()))));
        //// leMap.put(prid,leMap.get(prid).add(bills.getPhaseAmount()));
        // }
        //
        // }
        //
        // }

        List<ClientsVo> clientsVoList = new ArrayList<>();
        for (Clients clients : clientsList) {
            ClientsVo clientsVo = new ClientsVo();
            Chat chat = chatsMap.get(clients.getId());
            Clock clock = clockMap.get(clients.getId());
            if (chat != null) {
                clientsVo.setContent(chat.getContent());
                clientsVo.setContentHtml(chat.getContentHtml());
            }
            if (clock != null) {
                clientsVo.setRemindTime(clock.getRemindTime());
                clientsVo.setReason(clientsVo.getReason());
            }
            // if (!gysMap.isEmpty()){
            // String gays = gysMap.get(clients.getCompany());
            // BigDecimal decimal = leMap.get(gays);
            // clientsVo.setDebt(decimal);
            // }
            BeanUtils.copyProperties(clients, clientsVo);
            // 查询业务员
            if (clients.getSalesmanId() != null) {
                User user1 = userMapper.selectByIdWithDelete(clients.getSalesmanId());
                clientsVo.setUserName(user1.getNickName());
            }

            // 查询客户欠款金额
            // 查询客户未付款订单
            LambdaQueryWrapper<Order> orderLQW = new LambdaQueryWrapper<>();
            orderLQW.eq(Order::getClientsId, clients.getId()).ne(Order::getStatus, 1);
            List<String> orderIdList = orderMapper.selectList(orderLQW).stream().map(Order::getId)
                    .collect(Collectors.toList());
            if (orderIdList.size() == 0) {
                orderIdList.add("");
            }
            // 根据订单id查询未付款账单
            LambdaQueryWrapper<OrderBilling> orderBillingLQW = new LambdaQueryWrapper<>();
            orderBillingLQW.in(OrderBilling::getOrderId, orderIdList).ne(OrderBilling::getBillStatus, 1);
            List<OrderBilling> orderBillingList = orderBillingMapper.selectList(orderBillingLQW);
            // 计算总欠款金额
            BigDecimal totalAmount = new BigDecimal(0);
            if (orderBillingList.size() != 0) {
                for (OrderBilling orderBilling : orderBillingList) {
                    totalAmount = totalAmount.add(orderBilling.getAmount());
                }
            }
            clientsVo.setDebt(totalAmount);

            clientsVoList.add(clientsVo);
        }

        // 查询总数,并且合并返回vo
        Long total = clientsMapper.selectCount(queryWrapper);
        ClientsInfoVo clientsInfoVo = new ClientsInfoVo();
        clientsInfoVo.setClientsVoList(clientsVoList);
        clientsInfoVo.setTotal(total);
        return clientsInfoVo;
    }

    /**
     * 根据客户id查询交流记录
     * 
     * @param clientId
     * @return
     */
    @Override
    public List<Chat> selectChatByClientId(String clientId) {
        // 查询交流记录，根据客户id，最新的交流记录放在最前面
        LambdaQueryWrapper<Chat> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Chat::getClientsId, clientId);
        wrapper.orderByDesc(Chat::getCreateTime);
        List<Chat> chatList = chatMapper.selectList(wrapper);
        return chatList;
    }

    /**
     * 新增客户信息
     * 
     * @param clientsVo
     * @return
     */
    @Override
    @Transactional
    public Result insertClients(ClientsVo clientsVo) {
        // 查询是否已经存在该客户，如果存在则增加数量，根据电话，姓名，公司名称,地址(地址有多个使用like)（有一个重复就算重复）
        // 地址可能是多个地址，是字符串传入通过,分割的,取出地址放入list中
        if (clientsVo == null || clientsVo.getRemindTime() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        String[] split = clientsVo.getAddress().split(",");
        List<String> addressList = new ArrayList<>(Arrays.asList(split));
        LambdaQueryWrapper<Clients> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Clients::getName, clientsVo.getName())
                .or()
                .eq(Clients::getPhone, clientsVo.getPhone())
                .or()
                .eq(Clients::getCompany, clientsVo.getCompany())
                .or()
                .like(Clients::getAddress, addressList);
        List<Clients> clients1 = clientsMapper.selectList(wrapper);
        if (!clients1.isEmpty() && clientsVo.getIsFirst() == 0) {
            clients1.get(0).setTimes(clients1.get(0).getTimes() + 1);
            // clientsMapper.updateById(clients1);
            return Result.success("201", clients1);
            // return Result.success("该客户可能已经存在，确认新增客户?",clients1);
        }

        // 通过id查询业务员信息
        User user = userMapper.selectById(StpUtil.getLoginId().toString());

        // 创建客户
        Clients clients = new Clients();
        BeanUtils.copyProperties(clientsVo, clients);
        if (user.getRoleId().equals(RoleEnum.ROLE_3.getCodeToString()) && clientsVo.getIsSalesman() == 0) {
            // 为客户列表，登录账号为业务员
            // 设置为业务员
            clients.setSalesmanId(user.getId());
        }
        clients.setTimes(1);
        // 查询用户省市区
        // 取出最后一个字符串，看看是否有市，有市则是市，并且删除市，比如，北京市，删除市，剩下北京
        String province = clientsVo.getProvince();
        if (province.endsWith("市")) {
            province = province.substring(0, province.length() - 1);
            clients.setProvince(province);
        }
        clients.setDeleted(0);
        // 审核状态通过
        clients.setStatus(0);
        clientsMapper.insert(clients);

        // if (user.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString())){
        // // 管理员直接添加
        // clients.setStatus(0);
        // clientsMapper.insert(clients);
        // }else {
        // // 业务员则需要审核
        // clients.setStatus(1);
        // clientsMapper.insert(clients);
        // }

        // 创建交流记录
        // 通过用户姓名，手机号，公司查询刚刚新增用户信息
        // LambdaQueryWrapper<Clients> queryWrapper2 = new LambdaQueryWrapper<>();
        // queryWrapper2.eq(Clients::getName,clients.getName())
        // .eq(Clients::getPhone,clients.getPhone())
        // .eq(Clients::getCompany,clients.getCompany())
        // .eq(Clients::getSalesmanId,user.getId());
        // Clients two = clientsMapper.selectOne(queryWrapper2);

        // 通过公司名称查询一下供应商是否存在该公司名称,如果不存在,则将该公司添加到供应商中,
        // LambdaQueryWrapper<Suppliers> queryWrapper = new LambdaQueryWrapper<>();
        // queryWrapper.eq(Suppliers::getSuppliersName,clients.getCompany());
        // Suppliers selectOne = suppliersMapper.selectOne(queryWrapper);
        // //如果是空则添加到供应商中
        // if (selectOne==null){
        // Suppliers suppliers = new Suppliers();
        // suppliers.setSuppliersName(clients.getCompany());
        // suppliers.setSuppliersPhone(clients.getPhone());
        // suppliers.setSuppliersAddress(clientsVo.getAddress());
        // suppliersMapper.insert(suppliers);
        // }

        // 添加交流记录
        Chat chat = new Chat();
        chat.setClientsId(clients.getId());
        chat.setSalesmanId(user.getId());
        chat.setContent("<p></p>");
        chat.setContentHtml("<p></p>");
        chat.setDeleted(0);
        if (clientsVo.getContent() != null && !clientsVo.getContent().isEmpty()) {
            chat.setContent(clientsVo.getContent());
            chat.setContentHtml(clientsVo.getContent());
        }
        chatMapper.insert(chat);

        // 添加提醒时间
        Clock clock = new Clock();
        clock.setClientsId(clients.getId());
        clock.setDeleted(0);
        clock.setRemindUserId(user.getId());
        clock.setInterviewtype(clientsVo.getInterviewtype());
        clock.setRemindTime(clientsVo.getRemindTime());
        clock.setReason(clientsVo.getReason());
        clock.setEnabled(0); // 默认开启 0是开启 1是关闭
        clockMapper.insert(clock);

        // 添加备注
        if (clientsVo.getRemarkContent() != null) {
            Remarks remarks = new Remarks();
            remarks.setQueryId(clients.getId());
            remarks.setRemarkContent(clientsVo.getRemarkContent());
            remarksMapper.insert(remarks);
        }

        return Result.success("添加成功");
    }

    /**
     * 确认新增客户(已存在的客户情况下执行)
     * 
     * @param clientsVo
     * @return
     */
    @Override
    public Result confirmInsertClients(ClientsVo clientsVo) {
        // 创建客户
        Clients clients = new Clients();
        BeanUtils.copyProperties(clientsVo, clients);
        // 通过id查询业务员信息
        User userOne = userMapper.selectById(StpUtil.getLoginId().toString());
        clients.setSalesmanId(userOne.getId());
        clients.setTimes(1);
        // 查询用户省市区
        LambdaQueryWrapper<RegionCodeZft> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RegionCodeZft::getProvince, clientsVo.getProvince());
        queryWrapper.eq(RegionCodeZft::getCity, clientsVo.getCity());
        queryWrapper.eq(RegionCodeZft::getArea, clientsVo.getDistrict());
        RegionCodeZft one = regionCodeZftMapper.selectOne(queryWrapper);
        clients.setProvince(one.getProvince());
        clients.setCity(one.getCity());
        clients.setDistrict(one.getArea());
        int i1 = clientsMapper.insert(clients);

        // 创建交流记录
        // 查询客户id
        LambdaQueryWrapper<Clients> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Clients::getName, clientsVo.getName())
                .eq(Clients::getPhone, clientsVo.getPhone())
                .eq(Clients::getCompany, clientsVo.getCompany())
                .eq(Clients::getSalesmanId, userOne.getId());
        Clients two = clientsMapper.selectOne(queryWrapper2);

        Chat chat = new Chat();
        chat.setClientsId(two.getId());
        chat.setSalesmanId(userOne.getId());
        chat.setContent(clientsVo.getContent());
        chat.setContentHtml(clientsVo.getContent());

        // 查询业务员信息
        User user = userMapper.selectById(StpUtil.getLoginId().toString());
        // 添加提醒时间
        if (clientsVo.getRemindTime() != null) {
            Clock clock = new Clock();
            clock.setRemindUserId(user.getId());
            clock.setInterviewtype(clientsVo.getInterviewtype());
            clock.setRemindTime(clientsVo.getRemindTime());
            clock.setReason(clientsVo.getReason());
            clock.setEnabled(0); // 默认开启 0是开启 1是关闭
            clockMapper.insert(clock);
        }
        int i2 = chatMapper.insert(chat);
        return i1 + i2 > 1 ? Result.success() : Result.error();
    }

    /**
     * 客户继续添加交流记录
     * 
     * @param chat
     * @return
     */
    @Override
    public Result insertChat(Chat chat) {
        // 查询该客户是否存在
        Clients clients = clientsMapper.selectById(chat.getClientsId());
        if (clients == null) {
            return Result.error("该客户不存在");
        }
        // 查询业务员信息
        User user = userMapper.selectById(StpUtil.getLoginId().toString());
        chat.setSalesmanId(user.getId());
        chat.setDeleted(0);
        int insert = chatMapper.insert(chat);
        // 添加交流次数，先查询出该客户的交流次数
        clients.setTimes(clients.getTimes() + 1);
        insert += clientsMapper.updateById(clients);
        return insert > 1 ? Result.success("添加成功") : Result.error("添加失败");
    }

    /**
     * 通过id查询客户信息
     * 
     * @param id
     * @return
     */
    @Override
    public ClientsVo selectClientsById(String id) {
        Clients clients = clientsMapper.selectById(id);
        if (clients != null) {
            // 查询交流记录，通过修改时间排序，取出最新的一条交流记录
            LambdaQueryWrapper<Chat> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Chat::getClientsId, id);
            queryWrapper.orderByDesc(Chat::getUpdateTime);
            List<Chat> chats = chatMapper.selectList(queryWrapper);

            // 查询提醒时间
            LambdaQueryWrapper<Clock> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.eq(Clock::getClientsId, id);
            queryWrapper2.orderByDesc(Clock::getRemindTime);
            List<Clock> clocks = clockMapper.selectList(queryWrapper2);

            Chat chat = chats.get(0);
            Clock clock = clocks.get(0);
            ClientsVo clientsVo = new ClientsVo();
            BeanUtils.copyProperties(chat, clientsVo);
            BeanUtils.copyProperties(clock, clientsVo);
            BeanUtils.copyProperties(clients, clientsVo);

            LambdaQueryWrapper<Remarks> remarksLQW = new LambdaQueryWrapper<>();
            remarksLQW.eq(Remarks::getQueryId, clients.getId());
            Remarks remarks = remarksMapper.selectOne(remarksLQW);
            if (remarks != null) {
                clientsVo.setRemarkContent(remarks.getRemarkContent());
            }

            return clientsVo;
        }
        return null;
    }

    /**
     * 修改客户信息
     * 
     * @param clientsVo
     * @return
     */
    @Override
    @Transactional
    public Result updateClients(ClientsVo clientsVo) {
        if (clientsVo == null || clientsVo.getId() == null || clientsVo.getId().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 查询是否有该客户
        Clients clients = clientsMapper.selectById(clientsVo.getId());
        if (clients == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数错误");
        }
        // 复制值
        BeanUtils.copyProperties(clientsVo, clients);

        // 判断权限，管理员直接修改，业务员则需要审核
        User user = userMapper.selectById(StpUtil.getLoginIdAsString());
        boolean root = user.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString());

        // 查询用户省市区
        // 取出最后一个字符串，看看是否有市，有市则是市，并且删除市，比如，北京市，删除市，剩下北京
        String province = clientsVo.getProvince();
        if (province.endsWith("市")) {
            province = province.substring(0, province.length() - 1);
            clients.setProvince(province);
        }

        // //修改提醒时间
        // Clock clock = new Clock();
        // BeanUtils.copyProperties(clientsVo,clock);
        // LambdaQueryWrapper<Clock> queryWrapper2 = new LambdaQueryWrapper<>();
        // queryWrapper2.eq(Clock::getClientsId,clientsVo.getId());
        // List<Clock> clockList = clockMapper.selectList(queryWrapper2);
        // clock.setId(clockList.get(0).getId());
        // clockMapper.updateById(clock);

        if (root) {
            // 为管理员，直接修改
            if (clients.getStatus() != 0) {
                clients.setStatus(0);
            }
            // 修改客户信息
            if (clients.getUpdateExamine() != null && clients.getUpdateExamine() != 0) {
                // 删除缓存信息
                clientsCacheMapper.deleteCacheByClientsId(clients.getId());
            }
            clients.setUpdateExamine(0);
            clientsMapper.updateById(clients);

            // 修改最新的交流记录
            if (clientsVo.getContent() != null) {
                Chat chat = new Chat();
                chat.setContent(clientsVo.getContent());
                LambdaQueryWrapper<Chat> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Chat::getClientsId, clientsVo.getId());
                List<Chat> chatList = chatMapper.selectList(queryWrapper);
                chat.setId(chatList.get(0).getId());
                chatMapper.updateById(chat);
            }
        } else {
            if (clients.getStatus() != 0) {
                // 不为管理员，且审核状态为待审核，未通过，直接修改
                clients.setStatus(1);
                clientsMapper.updateById(clients);
            } else {
                // 不为管理员，审核状态为通过，放进缓存
                // 设置修改审核状态为待审核
                clients.setUpdateExamine(1);
                LambdaUpdateWrapper<Clients> clientsLUW = new LambdaUpdateWrapper<>();
                clientsLUW.eq(Clients::getId, clients.getId()).set(Clients::getUpdateExamine,
                        clients.getUpdateExamine());
                clientsMapper.update(null, clientsLUW);
                // 先查询是否有缓存
                LambdaQueryWrapper<ClientsCache> cacheLQW = new LambdaQueryWrapper<>();
                cacheLQW.eq(ClientsCache::getClientsId, clients.getId());
                ClientsCache clientsCache = clientsCacheMapper.selectOne(cacheLQW);
                if (clientsCache == null) {
                    // 添加缓存
                    clientsCache = new ClientsCache();
                    BeanUtils.copyProperties(clients, clientsCache);
                    clientsCache.setId(null);
                    clientsCache.setClientsId(clients.getId());
                    clientsCacheMapper.insert(clientsCache);
                } else {
                    ClientsCache cache = new ClientsCache();
                    BeanUtils.copyProperties(clients, cache);
                    cache.setId(clientsCache.getId());
                    cache.setClientsId(clients.getId());
                    clientsCacheMapper.updateById(cache);
                }
                // 查管理员角色
                LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
                userLQW.eq(User::getRoleId, RoleEnum.ROLE_1.getCodeToString())
                        .eq(User::getState, BaseEnum.USER_INCUMBENCY.getCodeInt());
                List<User> userList = userMapper.selectList(userLQW);
                if (!userList.isEmpty()) {
                    List<MessageNotification> msgList = new ArrayList<>();
                    for (User admin : userList) {
                        // 创建消息通知
                        MessageNotification msg = new MessageNotification();
                        msg.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                        // 标题
                        msg.setTitle("有新的客户信息修改申请待审批");
                        // 内容
                        String content = user.getNickName() + "申请修改客户（" + clients.getName() + "）的信息";
                        msg.setContent(content);
                        // 发布人为申请人
                        msg.setPublisherId(user.getId());
                        // 接收人为管理员
                        msg.setReceiverId(admin.getId());
                        // 关联id
                        msg.setRelevanceId(clients.getId());
                        // 类型为客户管理
                        msg.setMsgType(4);
                        // 子菜单为1客户列表
                        msg.setSubmenu(1);
                        // 状态为待处理
                        msg.setStatus(0);
                        msg.setCreateTime(new Date());
                        msgList.add(msg);
                    }
                    msgNotificationMapper.insertBatch(msgList);
                }
            }
        }

        // 修改备注
        if (clientsVo.getRemarkContent() != null) {
            // 查询是否有
            LambdaQueryWrapper<Remarks> remarksLQW = new LambdaQueryWrapper<>();
            remarksLQW.eq(Remarks::getQueryId, clients.getId());
            Remarks remarks = remarksMapper.selectOne(remarksLQW);
            if (remarks == null) {
                // 创建
                remarks = new Remarks();
                remarks.setQueryId(clients.getId());
                remarks.setRemarkContent(clientsVo.getRemarkContent());
                remarksMapper.insert(remarks);
            } else {
                remarks.setRemarkContent(clientsVo.getRemarkContent());
                remarksMapper.updateById(remarks);
            }
        }
        return Result.success("修改成功");
    }

    @Override
    public Result updateRemindTime(ClientsDto clientsDto) {
        if (clientsDto == null || (clientsDto.getId() == null || clientsDto.getRemindTime() == null)) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 查询是否有该客户
        Clients clients = clientsMapper.selectById(clientsDto.getId());
        if (clients == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数错误");
        }

        // 修改提醒时间
        Clock clock = new Clock();
        BeanUtils.copyProperties(clientsDto, clock);
        LambdaQueryWrapper<Clock> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Clock::getClientsId, clientsDto.getId());
        List<Clock> clockList = clockMapper.selectList(queryWrapper2);
        clock.setId(clockList.get(0).getId());
        clockMapper.updateById(clock);
        return Result.success("修改成功");
    }

    /**
     * 删除客户信息
     * 
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result deleteClientsById(String id) {
        if (id == null || id.isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        User user = userMapper.selectById(StpUtil.getLoginIdAsString());
        if (!user.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString())) {
            return new Result(HttpStatus.FORBIDDEN, "权限不足");
        }
        // 查询是否有该客户
        Clients clients = clientsMapper.selectById(id);
        if (clients == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该客户不存在");
        }
        // 删除客户
        clientsMapper.deleteById(clients.getId());
        // 删除预约提醒表
        LambdaQueryWrapper<Clock> clockLQW = new LambdaQueryWrapper<>();
        clockLQW.eq(Clock::getClientsId, clients.getId());
        clockMapper.delete(clockLQW);
        // 删除交流记录表
        LambdaQueryWrapper<Chat> chatLQW = new LambdaQueryWrapper<>();
        chatLQW.eq(Chat::getClientsId, clients.getId());
        chatMapper.delete(chatLQW);
        return Result.success("删除成功");
    }

    /**
     * 审核客户信息
     * 
     * @param type
     * @return
     */
    @Override
    public Result auditClients(String id, Integer type) {
        if (id == null || type == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }

        User user = userMapper.selectById(StpUtil.getLoginIdAsString());
        if (!user.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString())) {
            return new Result(HttpStatus.FORBIDDEN, "权限不足");
        }

        // 查询该用户是否存在
        Clients clients = clientsMapper.selectById(id);
        if (clients == null) {
            return Result.error("该客户不存在");
        }

        // 修改状态
        LambdaUpdateWrapper<Clients> clientsLUW = new LambdaUpdateWrapper<>();
        clientsLUW.eq(Clients::getId, id).set(Clients::getStatus, type);
        clientsMapper.update(null, clientsLUW);
        return Result.success("操作成功");
        // 查询当前用户是否有权限审核
        // LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        // queryWrapper.eq(User::getId,StpUtil.getLoginId());
        // User user = userMapper.selectOne(queryWrapper);
        // Role role = roleMapper.selectById(user.getRoleId());
        // if (role.getRoleType().equals("root")){
        // //修改审核状态
        // Clients clients = new Clients();
        // clients.setId(id);
        // clients.setStatus(type);
        // int i = clientsMapper.updateById(clients);
        //
        // return i>0?Result.success():Result.error();
        // }
    }

    /**
     * 通过搜索条件查询客户信息 客户姓名，客户电话，客户公司，客户地址来模糊查询客户信息
     * 
     * @param name
     * @return
     */
    @Override
    public ClientsInfoVo selectClientsBySearch(String name) {
        // 通过搜索，客户姓名，客户电话，客户公司，客户地址来模糊查询客户信息
        LambdaQueryWrapper<Clients> queryWrapper = new LambdaQueryWrapper<>();
        // 判断是否为管理员
        LambdaQueryWrapper<User> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(User::getId, StpUtil.getLoginId());
        User user = userMapper.selectOne(queryWrapper1);
        Role role = roleMapper.selectById(user.getRoleId());
        if (!user.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString())) {
            // 业务员查自己
            queryWrapper.eq(Clients::getSalesmanId, StpUtil.getLoginId()).eq(Clients::getStatus, 0)
                    .and(i -> i.like(Clients::getName, name)
                            .or().like(Clients::getPhone, name)
                            .or().like(Clients::getCompany, name)
                            .or().like(Clients::getAddress, name));
        } else {
            // 超级管理员查所有
            queryWrapper
                    .like(Clients::getName, name)
                    .or().like(Clients::getPhone, name)
                    .or().like(Clients::getCompany, name)
                    .or().like(Clients::getAddress, name);
        }

        List<Clients> clientsList = clientsMapper.selectList(queryWrapper);
        if (clientsList.size() < 1) {
            return new ClientsInfoVo();
        }

        List<ClientsVo> clientsVoList = new ArrayList<>();
        clientsList.stream().forEach(clients -> {
            ClientsVo clientsVo = new ClientsVo();
            BeanUtils.copyProperties(clients, clientsVo);

            clientsVoList.add(clientsVo);
        });

        // 封装返回数据
        ClientsInfoVo clientsInfoVo = new ClientsInfoVo();
        clientsInfoVo.setClientsVoList(clientsVoList);
        return clientsInfoVo;
    }

    /**
     * 分配客户给其他业务员
     * 
     * @param ids
     * @param userId
     * @return
     */
    @Override
    public Result dispatchClients(String ids, String userId) {
        // 判断是否为管理员
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, StpUtil.getLoginId());
        User user = userMapper.selectOne(queryWrapper);
        Role role = roleMapper.selectById(user.getRoleId());
        if (!role.getRoleType().equals("root")) {
            return Result.error("没有权限分配客户");
        }
        // 查询该业务员是否存在
        User salesman = userMapper.selectById(userId);
        if (salesman == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该业务员不存在");
        }

        // 分配客户给其他业务员
        String[] split = ids.split(",");
        Clients clients = new Clients();
        clients.setSalesmanId(salesman.getId());
        LambdaUpdateWrapper<Clients> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Clients::getId, split);
        int i = clientsMapper.update(clients, updateWrapper);
        // 逗号分隔
        return i > 0 ? Result.success("分配成功") : Result.error("分配失败");
    }

    /**
     * 业务员年月日，新增客户数量统计，根据类型统计,通过数量排序，最大的排在最前面
     * typeOne: 0:成交客户 1：意向客户 2：全部客户 typeTwo：0日，1月
     */
    @Override
    public Result selectClientsCountByType(Integer typeOne, Integer typeTwo) {
        // 查询业务员id
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRole::getNameZh, "业务员").eq(SysRole::getEnabled, 1);
        SysRole sysRole = sysRoleMapper.selectOne(queryWrapper);
        // 查询所有业务员信息
        LambdaQueryWrapper<User> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(User::getRoleId, sysRole.getId());
        List<User> userList = userMapper.selectList(queryWrapper1);
        if (userList.size() < 1) {
            return Result.error("没有业务员");
        }
        // 拿到所有业务员id
        List<String> collectId = userList.stream().map(User::getId).collect(Collectors.toList());
        // 获取当前日期,格式化时间
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = currentDate.format(formatter);
        // 查询这个月的新增客户数量
        String formattedFirstDay = null;
        String formattedLastDay = null;

        if (typeTwo == 1) {
            // 获取当前日期
            LocalDate currentDate2 = LocalDate.now();
            // 获取当前月的第一天
            LocalDate firstDayOfMonth = currentDate2.withDayOfMonth(1);
            // 获取当前月的最后一天
            LocalDate lastDayOfMonth = currentDate2.withDayOfMonth(currentDate2.lengthOfMonth());
            // 定义日期格式
            DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            // 格式化日期
            // 第一天
            formattedFirstDay = firstDayOfMonth.format(formatter2);
            // 最后一天
            formattedLastDay = lastDayOfMonth.format(formatter2);
        }

        // 查询业务员新增客户数量
        LambdaQueryWrapper<Clients> queryWrapper2 = new LambdaQueryWrapper<>();

        LambdaQueryWrapper<Clients> wrapper = Wrappers.lambdaQuery();
        wrapper.in(Clients::getSalesmanId, collectId)
                .groupBy(Clients::getSalesmanId)
                .select(Clients::getSalesmanId);
        if (typeTwo == 0) {
            wrapper.apply("DATE(create_time) = '" + formattedDate + "'");
        }
        if (typeTwo == 1) {
            wrapper.between(Clients::getCreateTime, formattedFirstDay, formattedLastDay);
        }
        List<Clients> clients = clientsMapper.selectList(wrapper);
        ChartsVo chartsVo = new ChartsVo();
        chartsVo.setChartsTwoVoList(new ArrayList<ChartsTwoVo>());
        for (Clients client : clients) {
            LambdaQueryWrapper<Clients> wrapper2 = Wrappers.lambdaQuery();
            wrapper2.eq(Clients::getSalesmanId, client.getSalesmanId());
            if (typeOne != 2) {
                wrapper2.eq(Clients::getType, typeOne);
            }
            if (typeTwo == 0) {
                wrapper2.apply("DATE(create_time) = '" + formattedDate + "'");
            }
            if (typeTwo == 1) {
                wrapper2.between(Clients::getCreateTime, formattedFirstDay, formattedLastDay);
            }
            Long invitedUsersCount = clientsMapper.selectCount(wrapper2);
            ChartsTwoVo chartsTwoVo = new ChartsTwoVo();
            chartsTwoVo.setId(client.getSalesmanId());
            chartsTwoVo.setCount(invitedUsersCount);
            chartsVo.getChartsTwoVoList().add(chartsTwoVo);
            System.out.println("salesmanId = " + client.getSalesmanId() + ", 数量是 " + invitedUsersCount);
        }
        // 拿到业务员id
        List<String> collect = chartsVo.getChartsTwoVoList().stream().map(ChartsTwoVo::getId)
                .collect(Collectors.toList());
        // 查询业务员信息
        if (collect.size() <= 0) {
            return Result.success(chartsVo);
        }
        LambdaQueryWrapper<User> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.in(User::getId, collect);
        List<User> userListSut = userMapper.selectList(queryWrapper3);
        // 查询当前业务员信息
        User selectById = userMapper.selectById(StpUtil.getLoginId().toString());

        Map<Object, User> map = new HashMap<>();
        userListSut.forEach(user -> {
            map.put(user.getId(), user);
        });

        for (ChartsTwoVo chartsTwoVo : chartsVo.getChartsTwoVoList()) {
            User user = map.get(chartsTwoVo.getId());
            if (chartsTwoVo.getId().equals(selectById.getId())) {
                chartsVo.setDaySum(chartsTwoVo.getCount());
                // if (typeTwo==0){
                // chartsVo.setDaySum(chartsTwoVo.getCount());
                // }
                // if (typeTwo==1){
                // chartsVo.setMonthSum(chartsTwoVo.getCount());
                // }
            }
            chartsTwoVo.setName(user.getNickName());
        }
        // 排序
        chartsVo.getChartsTwoVoList().sort((o1, o2) -> (int) (o2.getCount() - o1.getCount()));
        return Result.success(chartsVo);
    }

    @Override
    public Result getClientWithDelete(ClientsDto clientsDto) {
        if (clientsDto == null || clientsDto.getId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 查询客户
        Clients clients = clientsMapper.selectByIdWithDelete(clientsDto.getId());
        if (clients == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数错误");
        }
        return Result.success("查询成功", clients);
    }

    @Override
    public Result getClientsList(ClientsDto clientsDto) {
        if (clientsDto == null || (clientsDto.getCurrentPage() == null && clientsDto.getPageSize() == null)) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        Page<Clients> clientsPage = new Page<>(clientsDto.getCurrentPage(), clientsDto.getPageSize());
        // 条件查询
        LambdaQueryWrapper<Clients> clientsLQW = new LambdaQueryWrapper<>();
        clientsLQW.orderByDesc(Clients::getCreateTime); // 按创建时间大小排序
        // 管理员查全部，业务员查自己
        User user = userMapper.selectById(StpUtil.getLoginIdAsString());
        if ((clientsDto.getSalesmanId() == null || clientsDto.getSalesmanId().isEmpty()) &&
                clientsDto.getIsSalesman() == 0) {
            if (!user.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString())) {
                // 不等于管理员，查自己
                clientsLQW.eq(Clients::getSalesmanId, user.getId());
            }
        } else if ((clientsDto.getSalesmanId() != null && !clientsDto.getSalesmanId().isEmpty()) &&
                clientsDto.getIsSalesman() == 0) {
            // 按业务员查询
            clientsLQW.eq(Clients::getSalesmanId, clientsDto.getSalesmanId());
        }
        // 根据省查询
        if (clientsDto.getProvince() != null && clientsDto.getCity() == null && clientsDto.getDistrict() == null) {
            clientsLQW.eq(Clients::getProvince, clientsDto.getProvince());
        } else
        // 根据市查询
        if (clientsDto.getProvince() != null && clientsDto.getCity() != null && clientsDto.getDistrict() == null) {
            clientsLQW.eq(Clients::getProvince, clientsDto.getProvince())
                    .eq(Clients::getCity, clientsDto.getCity());
        } else
        // 根据区(县)查询
        if (clientsDto.getProvince() != null && clientsDto.getCity() != null && clientsDto.getDistrict() != null) {
            clientsLQW.eq(Clients::getProvince, clientsDto.getProvince())
                    .eq(Clients::getCity, clientsDto.getCity())
                    .eq(Clients::getDistrict, clientsDto.getDistrict());
        }
        // 根据客户类型查询
        if (clientsDto.getType() != null && clientsDto.getType() != 4) {
            clientsLQW.eq(Clients::getType, clientsDto.getType());
        }
        // 根据状态
        if (clientsDto.getStatus() != null) {
            clientsLQW.eq(Clients::getStatus, clientsDto.getStatus());
        }

        if (clientsDto.getIsSalesman() == 1) {
            // 公海池
            clientsLQW.isNull(Clients::getSalesmanId);
        } else {
            // 客户列表
            clientsLQW.isNotNull(Clients::getSalesmanId);
        }

        // 根据客户姓名，公司，电话号码，地址搜索
        if (clientsDto.getName() != null) {
            clientsLQW.and(i -> i.like(Clients::getName, clientsDto.getName())
                    .or().like(Clients::getCompany, clientsDto.getName())
                    .or().like(Clients::getPhone, clientsDto.getName())
                    .or().like(Clients::getAddress, clientsDto.getName()));
        }

        // List<Clients> clientsList = clientsMapper.selectPage(clientsPage,
        // clientsLQW).getRecords();
        List<Clients> clientsList = clientsMapper.selectList(clientsLQW);

        List<ClientsVo> clientsVoList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        if (clientsList.isEmpty()) {
            map.put("total", 0);
            map.put("clientsVoList", clientsVoList);
            return Result.success("查询成功", map);
        }

        List<String> clientsIdList = clientsList.stream().map(Clients::getId).collect(Collectors.toList());
        // 查询交流记录
        LambdaQueryWrapper<Chat> chatLQW = new LambdaQueryWrapper<>();
        chatLQW.in(Chat::getClientsId, clientsIdList);
        List<Chat> chatList = chatMapper.selectList(chatLQW);
        Map<String, Chat> chatsMap = chatList.parallelStream() // 使用并行流来加速处理过程
                .filter(chat -> chat.getClientsId() != null) // 确保clientsId非空
                .collect(Collectors.toMap(
                        Chat::getClientsId, // 键由Chat::getClientsId决定
                        Function.identity(), // 值就是流中的对象本身
                        (chat1, chat2) -> chat2 // 在遇到重复键时保留最后一个出现的Chat对象
                ));
        // 查询约谈内容
        List<Clock> clockList = clockMapper
                .selectList(new LambdaQueryWrapper<Clock>().in(Clock::getClientsId, clientsIdList));
        Map<String, Clock> clockMap = clockList.stream()
                .collect(Collectors.toMap(Clock::getClientsId, Function.identity()));

        // 获取业务员
        List<String> salesmanIdList = clientsList.stream().map(Clients::getSalesmanId).collect(Collectors.toList());
        if (salesmanIdList.isEmpty()) {
            salesmanIdList.add("");
        }
        List<User> userList = userMapper.selectBatchByIdWithDelete(salesmanIdList);
        // 根据业务员id获取业务员对象
        Map<String, User> userMap = new HashMap<>();
        if (userList.size() > 0) {
            userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        }

        // 获取客户未付款订单
        List<Order> orderList = orderMapper.selectBatchClientsIdWithDelete(clientsIdList, 0);
        orderList.addAll(orderMapper.selectBatchClientsIdWithDelete(clientsIdList, 2));
        List<String> orderIdList = orderList.stream().map(Order::getId).collect(Collectors.toList());
        if (orderIdList.isEmpty()) {
            orderIdList.add("");
        }
        // 根据clientsId获取订单列表
        Map<String, List<Order>> orderMap = new HashMap<>();
        for (Order order : orderList) {
            if (orderMap.containsKey(order.getClientsId())) {
                orderMap.get(order.getClientsId()).add(order);
            } else {
                List<Order> orders = new ArrayList<>();
                orders.add(order);
                orderMap.put(order.getClientsId(), orders);
            }
        }

        // 查询订单账单
        LambdaQueryWrapper<OrderBilling> orderBillingLQW = new LambdaQueryWrapper<>();
        orderBillingLQW.in(OrderBilling::getOrderId, orderIdList);
        List<OrderBilling> orderBillingList = orderBillingMapper.selectList(orderBillingLQW);
        // 根据订单id获取订单账单列表
        Map<String, List<OrderBilling>> orderBillingMap = new HashMap<>();
        for (OrderBilling orderBilling : orderBillingList) {
            if (orderBillingMap.containsKey(orderBilling.getOrderId())) {
                orderBillingMap.get(orderBilling.getOrderId()).add(orderBilling);
            } else {
                List<OrderBilling> orderBillings = new ArrayList<>();
                orderBillings.add(orderBilling);
                orderBillingMap.put(orderBilling.getOrderId(), orderBillings);
            }
        }

        // 获取备注
        LambdaQueryWrapper<Remarks> remarksLQW = new LambdaQueryWrapper<>();
        remarksLQW.in(Remarks::getQueryId, clientsIdList);
        List<Remarks> remarksList = remarksMapper.selectList(remarksLQW);
        // 根据客户id获取备注对象
        Map<String, Remarks> remarksMap = new HashMap<>();
        if (remarksList.size() > 0) {
            remarksMap = remarksList.stream().collect(Collectors.toMap(Remarks::getQueryId, r -> remarksList.stream()
                    .filter(remarks -> remarks.getQueryId().equals(r.getQueryId()))
                    .findFirst()
                    .orElse(null)));
        }

        for (Clients clients : clientsList) {
            ClientsVo clientsVo1 = new ClientsVo();
            Chat chat = chatsMap.get(clients.getId());
            Clock clock = clockMap.get(clients.getId());
            if (chat != null) {
                clientsVo1.setContent(chat.getContent());
                clientsVo1.setContentHtml(chat.getContentHtml());
            }
            if (clock != null) {
                clientsVo1.setRemindTime(clock.getRemindTime());
                clientsVo1.setReason(clientsVo1.getReason());
            }
            BeanUtils.copyProperties(clients, clientsVo1);
            // 查询业务员
            if (clients.getSalesmanId() != null) {
                User user1 = userMap.get(clients.getSalesmanId());
                clientsVo1.setUserName(user1.getNickName());
            }

            // 计算总欠款金额
            BigDecimal totalAmount = new BigDecimal(0);
            // 获取订单
            if (orderMap.containsKey(clients.getId())) {
                List<Order> orders = orderMap.get(clients.getId());
                for (Order order : orders) {
                    if (orderBillingMap.containsKey(order.getId())) {
                        List<OrderBilling> billingList = orderBillingMap.get(order.getId());
                        for (OrderBilling orderBilling : billingList) {
                            totalAmount = totalAmount.add(orderBilling.getAmount());
                        }
                    }
                }
            }
            clientsVo1.setDebt(totalAmount);

            // 获取备注
            if (remarksMap.containsKey(clients.getId())) {
                Remarks remarks = remarksMap.get(clients.getId());
                clientsVo1.setRemarkContent(remarks.getRemarkContent());
            }
            clientsVoList.add(clientsVo1);
        }

        if (clientsDto.getSortedType() == null) {
            clientsDto.setSortedType(0);
        }
        switch (clientsDto.getSortedType()) {
            case 0:
                break;
            case 1:
                clientsVoList = clientsVoList.stream().sorted(Comparator.comparing(ClientsVo::getDebt))
                        .collect(Collectors.toList());
                break;
            case -1:
                clientsVoList = clientsVoList.stream().sorted(Comparator.comparing(ClientsVo::getDebt).reversed())
                        .collect(Collectors.toList());
                break;
        }
        int listLength = clientsVoList.size();
        int selectPageStart = (int) ((clientsPage.getCurrent() - 1) * clientsPage.getSize());
        int selectPageEnd = (int) (clientsPage.getCurrent() * clientsPage.getSize());
        if (selectPageEnd > listLength) {
            selectPageEnd = listLength;
        }
        clientsVoList = clientsVoList.subList(selectPageStart, selectPageEnd);

        // map.put("total", clientsPage.getTotal());
        map.put("total", listLength);
        map.put("clientsVoList", clientsVoList);
        return Result.success("查询成功", map);
    }

    @Override
    public Result surrenderClients(ClientsDto clientsDto) {
        if (clientsDto == null || clientsDto.getId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        Clients clients = clientsMapper.selectById(clientsDto.getId());
        if (clients == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数错误");
        }
        // 移除业务员
        LambdaUpdateWrapper<Clients> clientsLUW = new LambdaUpdateWrapper<>();
        clientsLUW.eq(Clients::getId, clients.getId()).set(Clients::getSalesmanId, null);
        clientsMapper.update(null, clientsLUW);
        return Result.success("修改成功");
    }

    @Override
    public Result getClientsCache(ClientsDto clientsDto) {
        if (clientsDto == null || clientsDto.getId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 查询客户缓存信息
        LambdaQueryWrapper<ClientsCache> cacheLQW = new LambdaQueryWrapper<>();
        cacheLQW.eq(ClientsCache::getClientsId, clientsDto.getId());
        ClientsCache clientsCache = clientsCacheMapper.selectOne(cacheLQW);
        // 查询交流记录，通过修改时间排序，取出最新的一条交流记录
        LambdaQueryWrapper<Chat> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Chat::getClientsId, clientsCache.getClientsId());
        queryWrapper.orderByDesc(Chat::getUpdateTime);
        List<Chat> chats = chatMapper.selectList(queryWrapper);

        // 查询提醒时间
        LambdaQueryWrapper<Clock> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Clock::getClientsId, clientsCache.getClientsId());
        queryWrapper2.orderByDesc(Clock::getRemindTime);
        List<Clock> clocks = clockMapper.selectList(queryWrapper2);

        Chat chat = chats.get(0);
        Clock clock = clocks.get(0);
        ClientsVo clientsVo1 = new ClientsVo();
        BeanUtils.copyProperties(chat, clientsVo1);
        BeanUtils.copyProperties(clock, clientsVo1);
        BeanUtils.copyProperties(clientsCache, clientsVo1);
        clientsVo1.setId(clientsCache.getClientsId());

        LambdaQueryWrapper<Remarks> remarksLQW = new LambdaQueryWrapper<>();
        remarksLQW.eq(Remarks::getQueryId, clientsCache.getClientsId());
        Remarks remarks = remarksMapper.selectOne(remarksLQW);
        if (remarks != null) {
            clientsVo1.setRemarkContent(remarks.getRemarkContent());
        }

        return Result.success("查询成功", clientsVo1);
    }

    @Override
    public Result updateClientsApply(ClientsDto clientsDto) {
        if (clientsDto == null || clientsDto.getId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        User user = userMapper.selectById(StpUtil.getLoginIdAsString());
        // 查询是否有该客户和缓存信息
        Clients clients = clientsMapper.selectById(clientsDto.getId());
        LambdaQueryWrapper<ClientsCache> cacheLQW = new LambdaQueryWrapper<>();
        cacheLQW.eq(ClientsCache::getClientsId, clientsDto.getId());
        ClientsCache clientsCache = clientsCacheMapper.selectOne(cacheLQW);
        if (clients == null || clientsCache == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数错误");
        }
        // 判断是否通过
        LambdaUpdateWrapper<Clients> clientsLUW = new LambdaUpdateWrapper<>();
        clientsLUW.eq(Clients::getId, clients.getId());
        if (clientsDto.getUpdateExamine() == 0) {
            // 通过
            // 复制
            BeanUtils.copyProperties(clientsCache, clients);
            clients.setId(clientsCache.getClientsId());
            // 修改状态
            clients.setUpdateExamine(0);
            clientsLUW.set(Clients::getName, clients.getName())
                    .set(Clients::getCompany, clients.getCompany())
                    .set(Clients::getAge, clients.getAge())
                    .set(Clients::getSex, clients.getSex())
                    .set(Clients::getPhone, clients.getPhone())
                    .set(Clients::getMail, clients.getMail())
                    .set(Clients::getProvince, clients.getProvince())
                    .set(Clients::getCity, clients.getCity())
                    .set(Clients::getDistrict, clients.getDistrict())
                    .set(Clients::getAddress, clients.getAddress())
                    .set(Clients::getType, clients.getType())
                    .set(Clients::getUpdateExamine, clients.getUpdateExamine());
            // 删除缓存
            clientsCacheMapper.deleteCacheByClientsId(clientsCache.getClientsId());
        } else if (clientsDto.getUpdateExamine() == 2) {
            // 不通过
            clients.setUpdateExamine(2);
            clientsLUW.set(Clients::getUpdateExamine, clients.getUpdateExamine());
        }
        clientsMapper.update(null, clientsLUW);
        // 创建消息通知
        MessageNotification msg = new MessageNotification();
        // 标题
        String updateExamine;
        if (clients.getUpdateExamine() == 0) {
            // 申请通过
            updateExamine = "已通过";
        } else {
            // 申请未通过
            updateExamine = "未通过";
        }
        String title = "客户信息修改申请" + updateExamine;
        msg.setTitle(title);
        // 内容
        String content = "您修改客户（" + clients.getName() + "）信息的申请" + updateExamine;
        msg.setContent(content);
        // 发布人为审核人
        msg.setPublisherId(user.getId());
        // 接收人为申请人
        msg.setReceiverId(clientsCache.getSalesmanId());
        // 关联id
        msg.setRelevanceId(clients.getId());
        // 类型为客户管理
        msg.setMsgType(4);
        // 子菜单为1客户列表
        msg.setSubmenu(1);
        // 状态为待处理
        msg.setStatus(0);
        msgNotificationMapper.insert(msg);
        return Result.success("操作成功");
    }

    @Override
    public Result claimClients(ClientsDto clientsDto) {
        if (clientsDto == null || clientsDto.getId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 查询是否有该客户
        Clients clients = clientsMapper.selectById(clientsDto.getId());
        if (clients == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该客户不存在");
        }
        // 查询权限，只有业务员可以认领
        User user = userMapper.selectById(StpUtil.getLoginIdAsString());
        if (!user.getRoleId().equals(RoleEnum.ROLE_3.getCodeToString())) {
            return new Result(HttpStatus.FORBIDDEN, "只有业务员可认领");
        }
        // 更新数据
        LambdaUpdateWrapper<Clients> clientsLUW = new LambdaUpdateWrapper<>();
        clientsLUW.eq(Clients::getId, clients.getId()).set(Clients::getSalesmanId, user.getId());
        clientsMapper.update(null, clientsLUW);
        // 提醒时间也修改业务员
        LambdaUpdateWrapper<Clock> clockLUW = new LambdaUpdateWrapper<>();
        clockLUW.eq(Clock::getClientsId, clients.getId()).set(Clock::getRemindUserId, user.getId());
        clockMapper.update(null, clockLUW);
        return Result.success("修改成功");
    }

    @Override
    public Result rankingList(ClientsDto clientsDto) {
        if (clientsDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 查询所有业务员
        LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
        userLQW.eq(User::getRoleId, RoleEnum.ROLE_3.getCodeToString());
        List<User> userList = userMapper.selectList(userLQW);

        List<ClientsExpansion> clientsExpansionList = new ArrayList<>();
        if (clientsDto.getMonthOrDay() == null) {
            clientsExpansionList = clientsMapper.selectRanking(null, null, clientsDto.getType());
        } else if (clientsDto.getMonthOrDay() == 0) {
            clientsExpansionList = clientsMapper.selectRanking(LocalDate.now(), null, clientsDto.getType());
        } else if (clientsDto.getMonthOrDay() == 1) {
            clientsExpansionList = clientsMapper.selectRanking(null, YearMonth.now(), clientsDto.getType());
        }
        List<ClientsRankingVo> clientsRankingVoList = new ArrayList<>();
        if (clientsExpansionList.size() > 0) {
            for (ClientsExpansion clientsExpansion : clientsExpansionList) {
                for (User user : userList) {
                    if (user.getId().equals(clientsExpansion.getSalesmanId())) {
                        ClientsRankingVo clientsRankingVo = new ClientsRankingVo();
                        clientsRankingVo.setUserId(user.getId());
                        clientsRankingVo.setUserName(user.getNickName());
                        clientsRankingVo.setTotal(clientsExpansion.getTotal());
                        clientsRankingVoList.add(clientsRankingVo);
                    }
                }
            }
        }
        return Result.success("查询成功", clientsRankingVoList);
    }

    @Override
    public Result getContactDays() {
        Current current = currentMapper.selectById("2");
        return Result.success("查询成功", current);
    }

    @Override
    public Result updateContactDays(Current current) {
        current.setId("2");
        currentMapper.updateById(current);
        return Result.success("修改成功");
    }
}
